import {
  getInvoiceInfo
} from "../../../../api/other";
import {
  getSubscribeMessageAuth
} from "../../../../utils/util";
import {
  applyInvoice
} from "../../../../api/order";

// pages/institute/open/open.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    invoiceType: 0, // 0-个人 1-公司
    userTitle: '',
    companyTitle: '',
    taxNum: '',
    email: '',
    orderIds: [],
    price: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const price = options.price;
    const orderIds = options.orderIds.split(',');
    getInvoiceInfo().then(res => {
      this.setData({
        price,
        orderIds,
        email: res.email,
        companyTitle: res.companyTitle,
        taxNum: res.taxNum,
        title: res.title,
        invoiceType: res.taxNum ? 1 : 0
      })
    })
  },

  /**
   * 提交电子发票
   * @param {object} e 
   */
  handleCommit(e) {
    if (this.invoiceType === 0 && this.data.userTitle === '') {
      this.showToast('请输入发票抬头')
    } else if (this.invoiceType === 1 && this.data.companyTitle === '') {
      this.showToast('请输入发票抬头')
    } else if (this.invoiceType === 1 && this.data.taxNum === '') {
      this.showToast('请输入企业税号')
    } else if (!(/^[a-zA-Z0-9_-]+@([\.a-zA-Z0-9_-]+)+$/).test(this.data.email)) {
      this.showToast('请输入正确的邮箱');
    } else {
      // 申请发票开具通知
      console.log(this.data.taxNum)
      getSubscribeMessageAuth(['a6jTsES3WS0pQqztKboWIrAoaVH2cIyLaUveYXzmr1s']).then(() => {
        // TODO 提交
        applyInvoice({
          title: this.data.invoiceType == 1 ? this.data.companyTitle : this.data.title,
          taxNum: this.data.invoiceType == 1 ? this.data.taxNum : null,
          orderIds: this.data.orderIds,
          email: this.data.email,
        }).then(() => {
          wx.showToast({
            title: '提交成功',
          })
          wx.navigateBack({
            delta: 2,
          })
        })
      })
    }
  },

  /**
   * 发票类型切换
   * @param {*} e 
   */
  handleChangeInvoiceType(e) {
    this.setData({
      invoiceType: Number(e.currentTarget.dataset.type)
    })
  },

  /**
   * 邮箱
   * @param {object} e 
   */
  onInputEmail(e) {
    this.data.email = e.detail.value.trim();
    this.setData({
      isChange: true
    })
  },

  /**
   * 个人发票抬头
   * @param {object} e 
   */
  onInputCompanyTitle(e) {
    this.data.userTitle = e.detail.value.trim();
    this.setData({
      isChange: true
    })
  },

  /**
   * 企业发票抬头
   * @param {object} e 
   */
  onInputCompanyTitle(e) {
    this.data.companyTitle = e.detail.value.trim();
    this.setData({
      isChange: true
    })
  },

  /**
   * 企业税号
   * @param {object} e 
   */
  onInputTaxNumber(e) {
    this.data.taxNum = e.detail.value.trim();
    this.setData({
      isChange: true
    })
  },

  /**
   * 吐司
   * @param {string} msg 
   */
  showToast(msg) {
    wx.showToast({
      title: msg,
      icon: 'none'
    })
  }
})